package com.netsdk.demo.customize;

import static com.netsdk.lib.Utils.getOsPrefix;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;

import com.netsdk.demo.util.CaseMenu;
import com.netsdk.lib.NetSDKLib;
import com.netsdk.lib.ToolKits;
import com.netsdk.lib.NetSDKLib.NET_PTZ_PRESET;
import com.netsdk.lib.NetSDKLib.NET_PTZ_PRESET_LIST;
import com.netsdk.lib.callback.impl.DefaultDisconnectCallback;
import com.netsdk.lib.callback.impl.DefaultHaveReconnectCallBack;
import com.netsdk.lib.enumeration.EM_CFG_LC_LIGHT_TYPE;
import com.netsdk.lib.enumeration.EM_CFG_LC_MODE;
import com.netsdk.lib.enumeration.EM_NEW_CONFIG;
import com.netsdk.lib.structure.CFG_LIGHTING_V2_DAYNIGHT;
import com.netsdk.lib.structure.CFG_LIGHTING_V2_INFO;
import com.netsdk.lib.structure.CFG_LIGHTING_V2_UNIT;
import com.netsdk.lib.structure.NET_LIGHT_INFO;
import com.sun.jna.Memory;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;

/**
 * DVR相关功能
 */
public class DVRConfigDemo {
	// SDk对象初始化
	public static final NetSDKLib netsdk = NetSDKLib.NETSDK_INSTANCE;
	public static final NetSDKLib configsdk = NetSDKLib.CONFIG_INSTANCE;

	// 判断是否初始化
	private static boolean bInit = false;
	// 判断log是否打开
	private static boolean bLogOpen = false;
	// 设备信息
	private NetSDKLib.NET_DEVICEINFO_Ex deviceInfo = new NetSDKLib.NET_DEVICEINFO_Ex();
	// 登录句柄
	private NetSDKLib.LLong m_hLoginHandle = new NetSDKLib.LLong(0);

	// 回调函数需要是静态的，防止被系统回收
	// 断线回调
	private static NetSDKLib.fDisConnect disConnectCB = DefaultDisconnectCallback.getINSTANCE();
	// 重连回调
	private static NetSDKLib.fHaveReConnect haveReConnectCB = DefaultHaveReconnectCallBack.getINSTANCE();

	// 编码格式
	public static String encode;

	static {
		String osPrefix = getOsPrefix();
		if (osPrefix.toLowerCase().startsWith("win32-amd64")) {
			encode = "GBK";
		} else if (osPrefix.toLowerCase().startsWith("linux-amd64")) {
			encode = "UTF-8";
		}
	}

	/**
	 * 获取当前时间
	 */
	public static String GetDate() {
		SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return simpleDate.format(new java.util.Date()).replaceAll("[^0-9]", "-");
	}

	/**
	 * 初始化SDK库
	 */
	public static boolean Init() {
		bInit = netsdk.CLIENT_Init(disConnectCB, null);// 进程启动时，初始化一次
		if (!bInit) {
			System.out.println("Initialize SDK failed");
			return false;
		}
		// 配置日志
		DVRConfigDemo.enableLog();

		// 设置断线重连回调接口, 此操作为可选操作，但建议用户进行设置
		netsdk.CLIENT_SetAutoReconnect(haveReConnectCB, null);

		// 设置登录超时时间和尝试次数，可选
		// 登录请求响应超时时间设置为3S
		int waitTime = 3000;
		// 登录时尝试建立链接 1 次
		int tryTimes = 1;
		netsdk.CLIENT_SetConnectTime(waitTime, tryTimes);
		// 设置更多网络参数， NET_PARAM 的nWaittime ， nConnectTryNum 成员与 CLIENT_SetConnectTime
		// 接口设置的登录设备超时时间和尝试次数意义相同,可选
		NetSDKLib.NET_PARAM netParam = new NetSDKLib.NET_PARAM();
		// 登录时尝试建立链接的超时时间
		netParam.nConnectTime = 10000;
		// 设置子连接的超时时间
		netParam.nGetConnInfoTime = 3000;
		netsdk.CLIENT_SetNetworkParam(netParam);
		return true;
	}

	/**
	 * 打开 sdk log
	 */
	private static void enableLog() {
		NetSDKLib.LOG_SET_PRINT_INFO setLog = new NetSDKLib.LOG_SET_PRINT_INFO();
		File path = new File("sdklog/");
		if (!path.exists())
			path.mkdir();

		// 这里的log保存地址依据实际情况自己调整
		String logPath = path.getAbsoluteFile().getParent() + "\\sdklog\\" + "sdklog" + GetDate() + ".log";
		setLog.nPrintStrategy = 0;
		setLog.bSetFilePath = 1;
		System.arraycopy(logPath.getBytes(), 0, setLog.szLogFilePath, 0, logPath.getBytes().length);
		System.out.println(logPath);
		setLog.bSetPrintStrategy = 1;
		bLogOpen = netsdk.CLIENT_LogOpen(setLog);
		if (!bLogOpen)
			System.err.println("Failed to open NetSDK log");
	}

	/**
	 * 高安全登录
	 */
	public void loginWithHighLevel() {
		// 输入结构体参数
		NetSDKLib.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY pstlnParam = new NetSDKLib.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY() {
			{
				szIP = m_strIpAddr.getBytes();
				nPort = m_nPort;
				szUserName = m_strUser.getBytes();
				szPassword = m_strPassword.getBytes();
			}
		};
		// 输出结构体参数
		NetSDKLib.NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY pstOutParam = new NetSDKLib.NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY();

		// 写入sdk
		m_hLoginHandle = netsdk.CLIENT_LoginWithHighLevelSecurity(pstlnParam, pstOutParam);
		if (m_hLoginHandle.longValue() == 0) {
			System.err.printf("Login Device[%s] Port[%d]Failed. %s\n", m_strIpAddr, m_nPort,
					netsdk.CLIENT_GetLastError());
		} else {
			deviceInfo = pstOutParam.stuDeviceInfo; // 获取设备信息
			System.out.println("Login Success");
			System.out.println("Device Address：" + m_strIpAddr);
			System.out.println("设备包含：" + deviceInfo.byChanNum + "个通道");
		}
	}

	/**
	 * 退出
	 */
	public void logOut() {
		if (m_hLoginHandle.longValue() != 0) {
			netsdk.CLIENT_Logout(m_hLoginHandle);
			System.out.println("LogOut Success");
		}
	}

	/**
	 * 清理sdk环境并退出
	 */
	public static void cleanAndExit() {
		if (bLogOpen) {
			netsdk.CLIENT_LogClose(); // 关闭sdk日志打印
		}
		netsdk.CLIENT_Cleanup(); // 进程关闭时，调用一次
		System.exit(0);
	}


	/**
	 * 获取当前云台的预置点列表
	 */
	public void getPresetList() {
		int MAX_QUERY_PRESET_NUM = 20; // 目前设置的最大查询预置点个数，根据实际调整
		int nType = NetSDKLib.NET_DEVSTATE_PTZ_PRESET_LIST;
		NET_PTZ_PRESET_LIST stuPresetList = new NET_PTZ_PRESET_LIST();

		NET_PTZ_PRESET[] arrPreset = new NET_PTZ_PRESET[MAX_QUERY_PRESET_NUM];
		for (int i = 0; i < arrPreset.length; i++) {
			arrPreset[i] = new NET_PTZ_PRESET();
		}

		stuPresetList.dwMaxPresetNum = arrPreset.length;
		int nMemoryLen = arrPreset[0].size() * stuPresetList.dwMaxPresetNum;
		stuPresetList.pstuPtzPorsetList = new Memory(nMemoryLen); // 申请内存
		stuPresetList.pstuPtzPorsetList.clear(nMemoryLen);
		ToolKits.SetStructArrToPointerData(arrPreset, stuPresetList.pstuPtzPorsetList); // 将数组内存拷贝到Pointer
		int nChannel = 0; // 通道号
		stuPresetList.write();
		IntByReference intRetLen = new IntByReference();
		if (netsdk.CLIENT_QueryRemotDevState(m_hLoginHandle,nType,nChannel,stuPresetList.getPointer(), stuPresetList.size(), intRetLen, 5000)) {		
		//if(netsdk.CLIENT_QueryDevState(m_hLoginHandle,  nType, stuPresetList.getPointer(), stuPresetList.size(), intRetLen, 5000)) {
			stuPresetList.read();
			ToolKits.GetPointerDataToStructArr(stuPresetList.pstuPtzPorsetList, arrPreset);
			System.out.println("返回预置点个数: " + stuPresetList.dwRetPresetNum);
			for (int i = 0; i < stuPresetList.dwRetPresetNum; ++i) {
				try {
					System.out.println(" 编号:"+arrPreset[i].nIndex);
					System.out.println(" 名称:"+new String(arrPreset[i].szName, encode));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		} else {
			System.err.println("QueryDevState Failed!" + ToolKits.getErrorCode());
		}
	}
	

	
	/**
	 * 转至预置点
	 */
	public void MovePreset() {		
		int dwPTZCommand = NetSDKLib.NET_PTZ_ControlType.NET_PTZ_POINT_MOVE_CONTROL;
		int nPresetIndex = 2; 	// 预置点值，从1开始
		if(PTZControl(dwPTZCommand, 0, nPresetIndex, 0, 0, null)) {
			System.out.println("MovePreset success!");
		} else {
			System.err.println("MovePreset Failed!" + ToolKits.getErrorCode());
		}
	}
	
	private int nQueryChannel = 0;// 通道号
	
	public boolean PTZControl(int dwPTZCommand, int lParam1, int lParam2, int lParam3, int dwStop, Pointer param4) {		
		return netsdk.CLIENT_DHPTZControlEx2(m_hLoginHandle, nQueryChannel, dwPTZCommand, lParam1, lParam2, lParam3, dwStop,param4);
	}

	
	private int serialNum = 1;
	/**
	 * 同步方式抓图 , 建议抓拍的频率不要超过1s
	 */
	public void syncSnapPicture() {
		
		NetSDKLib.NET_IN_SNAP_PIC_TO_FILE_PARAM snapParamIn = new NetSDKLib.NET_IN_SNAP_PIC_TO_FILE_PARAM();
		NetSDKLib.NET_OUT_SNAP_PIC_TO_FILE_PARAM snapParamOut = new NetSDKLib.NET_OUT_SNAP_PIC_TO_FILE_PARAM(1024 * 1024);
		
		snapParamIn.stuParam.Channel = 0;
		snapParamIn.stuParam.Quality = 3;
		snapParamIn.stuParam.ImageSize = 1; // 0：QCIF,1：CIF,2：D1
		snapParamIn.stuParam.mode = 0; // -1:表示停止抓图, 0：表示请求一帧, 1：表示定时发送请求, 2：表示连续请求
		snapParamIn.stuParam.InterSnap = 5;
		snapParamIn.stuParam.CmdSerial = serialNum;
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyMMddHHmmss");
		final String fileName = "SyncSnapPicture_" + dateFormat.format(new Date()) + "_" + serialNum + ".jpg";
		System.arraycopy(fileName.getBytes(), 0, snapParamIn.szFilePath, 0, fileName.getBytes().length);
		
		final int timeOut = 5000; // 5 second


		Pointer pInbuf =new Memory(snapParamIn.size());
		ToolKits.SetStructDataToPointer(snapParamIn, pInbuf, 0);

		Pointer pOutbuf =new Memory(snapParamOut.size());
		ToolKits.SetStructDataToPointer(snapParamOut, pOutbuf, 0);

		if (!netsdk.CLIENT_SnapPictureToFile(m_hLoginHandle, pInbuf, pOutbuf, timeOut)) {
			System.err.printf("CLIENT_SnapPictureEx Failed ! Last Error[%x]\n", netsdk.CLIENT_GetLastError());
			return;
		}

		ToolKits.GetPointerData(pOutbuf,snapParamOut);
		Pointer szPicBuf = snapParamOut.szPicBuf;
		byte[] byteArray = szPicBuf.getByteArray(0, snapParamOut.dwPicBufRetLen);
		System.out.println("CLIENT_SnapPictureToFile Success. " + new File(fileName).getAbsolutePath());
	}
	
	
    private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private void setTime(Calendar calendar, NetSDKLib.NET_TIME stuTime) {
        stuTime.setTime(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH),
                calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
    }
	
    // 下载句柄
    private NetSDKLib.LLong m_hDownLoadHandle = new NetSDKLib.LLong(0);
    
    /**
     * 下载录像 转码流 通用接口 可以从回调获取转码流数据
     */
    public void downloadRecordFileWithConvertedDataType() {

        int nStreamType = 0;         // 0-主辅码流,1-主码流,2-辅码流
        int nChannel = 0;            // 通道号
        int nType = 0;               // 文件类型
        NetSDKLib.NET_TIME stTimeStart = new NetSDKLib.NET_TIME();    // 开始时间
        NetSDKLib.NET_TIME stTimeEnd = new NetSDKLib.NET_TIME();      // 结束时间

        Calendar calendar = Calendar.getInstance();

        @SuppressWarnings("resource")
        Scanner scanner = new Scanner(System.in);
        try {
            // 请选择要下载的码流 0-主辅码流,1-主码流,2-辅码流
            nStreamType = 1;   // 默认主码流

            System.out.println("请输入真实通道号(注意sdk从0开始计数): ");
            nChannel = scanner.nextInt();

            //        0 私有码流
            //        1 国标PS码流
            //        2 TS码流
            //        3 MP4文件(从回调函数出来的是私有码流数据,参数dwDataType值为0)
            //        4 裸H264码流
            //        5 流式FLV
            // 请输入保存的文件类型 码流转换类型 0 私有码流; 1 国标PS码流; 2 TS码流; 3 MP4文件; 4 裸H264码流; 5 流式FLV");
            nType = 4;     // 转成 裸H264码流
            //nType = 3;     // 转成 MP4文件
            System.out.println("请输入录像开始时间(格式:yyyy-MM-dd HH:mm:ss): ");
            String startTime = scanner.next().trim() + " " + scanner.next().trim();
            calendar.setTime(format.parse(startTime));
            setTime(calendar, stTimeStart);

            System.out.println("请输入录像结束时间(格式:yyyy-MM-dd HH:mm:ss): ");
            String endTime = scanner.next().trim() + " " + scanner.next().trim();
            calendar.setTime(format.parse(endTime));
            setTime(calendar, stTimeEnd);
        } catch (ParseException e) {
            System.err.println("时间输入非法");
            return;
        }

        File dir = new File("RecordFiles");
        if (!dir.exists()) {// 判断目录是否存在
            dir.mkdir();
        }

        String savedFileName = "RecordFiles/RecordCovertTest" + System.currentTimeMillis() + ".dav"; // 保存录像文件名
        this.downloadRecordFileConverted(nStreamType, nChannel, stTimeStart, stTimeEnd, savedFileName, nType);
    }

    /**
     * 下载录像，通用接口(把原始码流转换成其他封装格式的码流)
     */
    public void downloadRecordFileConverted(int nStreamType, int nChannel,
                                            NetSDKLib.NET_TIME stTimeStart, NetSDKLib.NET_TIME stTimeEnd,
                                            String savedFileName, int nType) {

        if (!setStreamType(nStreamType)) {
            System.err.println("Set Stream Type Failed!." + ToolKits.getErrorCode());
            return;
        }

        NetSDKLib.NET_IN_DOWNLOAD_BY_DATA_TYPE stIn = new NetSDKLib.NET_IN_DOWNLOAD_BY_DATA_TYPE();

        stIn.emDataType = nType;            // 封装类型
        stIn.emRecordType = NetSDKLib.EM_QUERY_RECORD_TYPE.EM_RECORD_TYPE_ALL; // 所有录像
        stIn.nChannelID = nChannel;
        stIn.stStartTime = stTimeStart;     // 开始时间
        stIn.stStopTime = stTimeEnd;        // 结束时间
        stIn.cbDownLoadPos = DownloadPosCallback.getInstance();           // 下载监控回调函数
        stIn.dwPosUser = null;
        stIn.fDownLoadDataCallBack = DownLoadDataCallBack.getInstance();  // 下载数据回调函数
        stIn.dwDataUser = null;
        stIn.szSavedFileName = savedFileName;

        NetSDKLib.NET_OUT_DOWNLOAD_BY_DATA_TYPE stOut = new NetSDKLib.NET_OUT_DOWNLOAD_BY_DATA_TYPE();
        stIn.write();
        stOut.write();
        m_hDownLoadHandle = netsdk.CLIENT_DownloadByDataType(m_hLoginHandle, stIn.getPointer(), stOut.getPointer(), 5000);
        if (m_hDownLoadHandle.longValue() != 0) {
            System.out.println("DownloadByDataType Succeed!");
        } else {
            System.err.println("DownloadByDataType Failed! " + ToolKits.getErrorCode());
        }
    }
    
    
    /**
     * 设置回放时的码流类型: 主码流/辅码流
     *
     */
    public boolean setStreamType(int m_streamType) {
        int emType = NetSDKLib.EM_USEDEV_MODE.NET_RECORD_STREAM_TYPE; // 回放录像枚举
        IntByReference steamType = new IntByReference(m_streamType);  // 0-主辅码流,1-主码流,2-辅码流
        return netsdk.CLIENT_SetDeviceMode(m_hLoginHandle, emType, steamType.getPointer());
    }
    
    /**
     * 下载数据回调，这里可以拿到原始的二进制码流数据
     * 回调写成单例模式, 如果回调里需要处理数据，请另开线程
     */
    public static class DownLoadDataCallBack implements NetSDKLib.fDataCallBack {

        private DownLoadDataCallBack() {
        }

        private static class DownloadDataCallBackHolder {
            private static final DownLoadDataCallBack dataCB = new DownLoadDataCallBack();
        }

        public static DownLoadDataCallBack getInstance() {
            return DownLoadDataCallBack.DownloadDataCallBackHolder.dataCB;
        }

        @Override
		public int invoke(NetSDKLib.LLong lRealHandle, int dwDataType, Pointer pBuffer, int dwBufSize, Pointer dwUser) {

            // byte[] data = pBuffer.getByteArray(0, dwBufSize);   // 这是二进制码流数据, 如果有其他用途可以从这里取出来
        	System.out.println("dwDataType [ " + dwDataType + " ]");
            // 不同的封装类型，回调里返回的 dwDataType 是不同的，它们遵循下面的逻辑
            if (dwDataType == (NetSDKLib.NET_DATA_CALL_BACK_VALUE + NetSDKLib.EM_REAL_DATA_TYPE.EM_REAL_DATA_TYPE_PRIVATE)) {
                System.out.println("DownLoad DataCallBack [ " + dwDataType + " ]");
            } else if (dwDataType == (NetSDKLib.NET_DATA_CALL_BACK_VALUE + NetSDKLib.EM_REAL_DATA_TYPE.EM_REAL_DATA_TYPE_GBPS)) {
                System.out.println("DownLoad DataCallBack [ " + dwDataType + " ]");
            } else if (dwDataType == (NetSDKLib.NET_DATA_CALL_BACK_VALUE + NetSDKLib.EM_REAL_DATA_TYPE.EM_REAL_DATA_TYPE_TS)) {
                System.out.println("DownLoad DataCallBack [ " + dwDataType + " ]");
            } else if (dwDataType == (NetSDKLib.NET_DATA_CALL_BACK_VALUE + NetSDKLib.EM_REAL_DATA_TYPE.EM_REAL_DATA_TYPE_MP4)) {
                System.out.println("DownLoad DataCallBack [ " + dwDataType + " ]");
            } else if (dwDataType == (NetSDKLib.NET_DATA_CALL_BACK_VALUE + NetSDKLib.EM_REAL_DATA_TYPE.EM_REAL_DATA_TYPE_H264)) {
                System.out.println("DownLoad DataCallBack [ " + dwDataType + " ]");
            } else if (dwDataType == (NetSDKLib.NET_DATA_CALL_BACK_VALUE + NetSDKLib.EM_REAL_DATA_TYPE.EM_REAL_DATA_TYPE_FLV_STREAM)) {
                System.out.println("DownLoad DataCallBack [ " + dwDataType + " ]");
            }
            return 0;
        }
    }

    /**
     * 下载进度回调函数
     * 回调写成单例模式, 如果回调里需要处理数据，请另开线程
     */
    public static class DownloadPosCallback implements NetSDKLib.fDownLoadPosCallBack {

        private DownloadPosCallback() {
        }

        private static class CallBackHolder {
            private static final DownloadPosCallback callback = new DownloadPosCallback();
        }

        public static DownloadPosCallback getInstance() {
            return DownloadPosCallback.CallBackHolder.callback;
        }

        @Override
        public void invoke(NetSDKLib.LLong lPlayHandle, int dwTotalSize, int dwDownLoadSize, Pointer dwUser) {

            System.out.println(String.format("dwDownLoadSize: %d || dwTotalSize: %d ", dwDownLoadSize, dwTotalSize));                      
            if (dwDownLoadSize == -1) {         // 下载结束
                System.out.println("Downloading Complete. ");
                new StopDownloadTask(lPlayHandle).start();   // 注意这里需要另起线程
            }
        }

        private static class StopDownloadTask extends Thread {
            private final NetSDKLib.LLong lDownloadHandle;

            public StopDownloadTask(NetSDKLib.LLong lDownloadHandle) {
                this.lDownloadHandle = lDownloadHandle;
            }

            @Override
			public void run() {
                stopDownLoadRecordFile(lDownloadHandle);
            }
        }
    }

    /**
     * 停止下载录像
     *
     * @param hDownLoadHandle 下载句柄
     */
    private static void stopDownLoadRecordFile(NetSDKLib.LLong hDownLoadHandle) {
        if (hDownLoadHandle.longValue() == 0) {
            return;
        }
        netsdk.CLIENT_StopDownload(hDownLoadHandle);
    }

    
    /**
     * 停止下载录像
     */
    public void stopDownLoadRecordFile() {
        stopDownLoadRecordFile(m_hDownLoadHandle);
    }
    	
	
	/**
	 * 获取摄像头通道列表
	 */
	public void getMatrixCamerasInfo () {	
		int cameraCount = deviceInfo.byChanNum;  // 通道号个数
		NetSDKLib.NET_MATRIX_CAMERA_INFO[]  cameraInfo = new NetSDKLib.NET_MATRIX_CAMERA_INFO[cameraCount];
		for(int i = 0; i < cameraCount; i++) {
			cameraInfo[i] = new NetSDKLib.NET_MATRIX_CAMERA_INFO();
		}
		
		// 入参
		NetSDKLib.NET_IN_MATRIX_GET_CAMERAS inMatrix = new NetSDKLib.NET_IN_MATRIX_GET_CAMERAS();
		
		// 出参
		NetSDKLib.NET_OUT_MATRIX_GET_CAMERAS outMatrix = new NetSDKLib.NET_OUT_MATRIX_GET_CAMERAS();
		outMatrix.nMaxCameraCount = cameraCount;
		outMatrix.pstuCameras = new Memory(cameraInfo[0].size() * cameraCount);
		outMatrix.pstuCameras.clear(cameraInfo[0].size() * cameraCount);
		
		ToolKits.SetStructArrToPointerData(cameraInfo, outMatrix.pstuCameras);  // 将数组内存拷贝到Pointer
		
		if(netsdk.CLIENT_MatrixGetCameras(m_hLoginHandle, inMatrix, outMatrix, 5000)) {
			ToolKits.GetPointerDataToStructArr(outMatrix.pstuCameras, cameraInfo);  // 将 Pointer 的内容 输出到   数组
			
			for(int j = 0; j < outMatrix.nRetCameraCount; j++) {
				if(cameraInfo[j].bRemoteDevice == 0) {   // 过滤远程设备
					continue;
				}
				System.out.println("通道号：" + cameraInfo[j].nChannelID);
				System.out.println("IP : " + new String(cameraInfo[j].stuRemoteDevice.szIp).trim());
				System.out.println("nPort : " + cameraInfo[j].stuRemoteDevice.nPort);
				System.out.println("szUser : " + new String(cameraInfo[j].stuRemoteDevice.szUser).trim());
				System.out.println("szPwd : " + new String(cameraInfo[j].stuRemoteDevice.szPwd).trim());
				System.out.println("通道个数 : " + cameraInfo[j].stuRemoteDevice.nVideoInputChannels);
			}
		} else {
			System.err.println("MatrixGetCameras Failed." + ToolKits.getErrorCode());
		}
	}
	
	/**
	 * 全彩相机补光灯灵敏度配置
	 */
	public void cfgCmdLightingV2() {
		String command = EM_NEW_CONFIG.CFG_CMD_LIGHTING_V2.getValue();
		int channel = 7;// 通道号
		CFG_LIGHTING_V2_INFO info = new CFG_LIGHTING_V2_INFO();
		// 获取配置
		if (ToolKits.GetDevConfig(m_hLoginHandle, channel, command, info)) {
			System.out.println("通道 : " + info.nChannel);
			System.out.println("白天黑夜对应灯光配置数量:"+info.nDNLightInfoNum);
			CFG_LIGHTING_V2_DAYNIGHT[] anDNLightInfo = info.anDNLightInfo;// 白天黑夜对应灯光配置 从元素0开始分别表示 白天、夜晚、普通、顺光、一般逆光、强逆光、低照度、自定义
			/**--------白天-----------*/ 
			int nLightInfoLen =anDNLightInfo[0].nLightInfoLen; 
			System.out.println("灯光类型数量: "+nLightInfoLen);
			CFG_LIGHTING_V2_UNIT[] anLightInfo = anDNLightInfo[0].anLightInfo;// 获取白天下的补光灯配置信息
			for (int i = 0; i < nLightInfoLen; i++) {
				System.out.println("------------------");
				System.out.println("灯光类型:"+EM_CFG_LC_LIGHT_TYPE.getNoteByValue(anLightInfo[i].emLightType));
				System.out.println("灯光模式:"+EM_CFG_LC_MODE.getNoteByValue(anLightInfo[i].emMode));
				System.out.println("近光灯组数量 :"+anLightInfo[i].nNearLightLen);
				NET_LIGHT_INFO[] anNearLight = anLightInfo[i].anNearLight;
				for (int j = 0; j < anLightInfo[i].nNearLightLen; j++) {
					System.out.println("亮度百分比:"+anNearLight[j].nLight);
				}
			}
			// 设置，在获取配置的基础上设置	
			// 配置文件 -白天    配置文件 - 白光模式   模式-手动   模式- 0-100
			info.anDNLightInfo[0].anLightInfo[1].anNearLight[0].nLight = 50;									
			if (ToolKits.SetDevConfig(m_hLoginHandle, channel, command, info)) {
				System.out.println("Set CFG_CMD_LIGHTING_V2 Succeed!");
			} else {
				System.err.println("Set CFG_CMD_LIGHTING_V2 Failed!" + netsdk.CLIENT_GetLastError());
			}
		} else {
			System.err.println("Get CFG_CMD_LIGHTING_V2 Failed!" + netsdk.CLIENT_GetLastError());
		}
	}
	
	/******************************** 测试控制台 ***************************************/

	// 配置登陆地址，端口，用户名，密码
	private String m_strIpAddr = "172.11.1.111";//172.11.1.111  172.11.222.228
	private int m_nPort = 37777;
	private String m_strUser = "admin";
	private String m_strPassword = "admin123";

	public static void main(String[] args) {
		DVRConfigDemo demo = new DVRConfigDemo();
		demo.InitTest();
		demo.RunTest();
		demo.EndTest();

	}

	/**
	 * 初始化测试
	 */
	public void InitTest() {
		DVRConfigDemo.Init();
		this.loginWithHighLevel();
	}

	/**
	 * 加载测试内容
	 */
	public void RunTest() {
		CaseMenu menu = new CaseMenu();
		// 通过SDK对接硬盘录像机，获取指定球机摄像头所设预置点位列表（含守望点）的接口
		menu.addItem(new CaseMenu.Item(this, "获取当前云台的预置点列表", "getPresetList"));
		// 通过SDK对接硬盘录像机，控制指定球机摄像头自带照明设备开关的接口
		menu.addItem(new CaseMenu.Item(this, "全彩相机补光灯灵敏度配置", "cfgCmdLightingV2"));
		// 通过SDK对接硬盘录像机，控制指定球机摄像头转到指定预置位的接口
		menu.addItem(new CaseMenu.Item(this, "转至预置点" , "MovePreset"));
		// 通过SDK对接硬盘录像机，控制指定摄像头截取视频画面的接口
		menu.addItem(new CaseMenu.Item(this, "同步方式抓图 ", "syncSnapPicture"));
		// 通过SDK对接硬盘录像机，控制指定摄像头的某一时间段的视频流的接口，接口需反馈基于H.264编码的视频片段，并能启动下载、查看下载进度、停止下载。
        menu.addItem(new CaseMenu.Item(this, "按时间下载录像(通用转码流接口)", "downloadRecordFileWithConvertedDataType"));
        menu.addItem(new CaseMenu.Item(this, "停止下载录像", "stopDownLoadRecordFile"));
        // 通过SDK对接硬盘录像机，查询摄像头通道列表 
        menu.addItem(new CaseMenu.Item(this, "获取摄像头通道列表", "getMatrixCamerasInfo"));
		menu.run();
	}

	/**
	 * 结束测试
	 */
	public void EndTest() {
		System.out.println("End Test");
		this.logOut(); // 登出设备
		System.out.println("See You...");
		DVRConfigDemo.cleanAndExit(); // 清理资源并退出
	}
	/******************************** 结束 ***************************************/

}
